﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace SystemScanner.ClientServices
{
	public class InstalledHotfixService
	{
		public static void AddHotfixesToScan(Data.Scan scan)
		{
			foreach (var hf in GetHotfixesForLocalComputer())
			{
				if (scan.Hotfixes.Any(x => x.Identifier == hf.Identifier) == false)
				{
					scan.Hotfixes.Add(hf);
				}
			}
		}
		public static IEnumerable<Data.Hotfix> GetHotfixesForLocalComputer()
		{
			// get list of all hotfixes
			var hotfixes = WmiService.GetInstancesOfClass("Win32_QuickFixEngineering");
			
			// remove the crap - not sure why all the "File 1" values are returned, but
			// this seems like a normal thing to do based on code samples around the net
			var meaningfulHotfixes =
				from hf in hotfixes
				where (hf["HotFixID"] as string) != "File 1"
				select hf;

			var hotfixDeDupe = new List<string>();

			foreach (var queriedValue in meaningfulHotfixes)
			{
				var id = queriedValue["HotFixID"] as string;

				// On some machines, hotfix id's have been found to be duplicated. Avoid this...
				if (hotfixDeDupe.Contains(id))
				{
					continue;
				}

				hotfixDeDupe.Add(id);

				var cap = queriedValue["Caption"] as string;
				var desc = queriedValue["Description"] as string;

				//Console.WriteLine("Hotfix: {0}", id);
				//var installon = queryObj["InstalledOn"] as string;
				//var installby = queryObj["InstalledBy"] as string;
				var newHotfix = new Data.Hotfix
				{
					Description = desc,
					Identifier = id,
					InformationalUrl = (cap ?? "")
				};
				yield return newHotfix;
			}
		}
	}
}